﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ExitGames.Client.Photon;
using ExitGames.Client.Photon.Lite;
using DICE_GS;

public class LoadingSceneManager : MonoBehaviour
{
    private static Queue<Dictionary<byte, object>> packetQueue;

	public static bool InputTouch = false;

	public GameObject LabelBG;
	public GameObject WelcomeLabel;
    public GameObject VersionLabel;
	public GameObject FacebookBtn;
	public GameObject TouchBtn;
	public GameObject TouchCollider;

    public UILabel loadingText;
    public UISlider progressBar;

    public UITexture facebookUserImageObject;
    public UILabel facebookUserNameText;

    bool isFinishedLoadUserData = false;

    public static LoadingSceneManager singleton;
	
	public static bool isForcedReLogin = false;

	public GameObject titleImage;
	public GameObject customServerAddressInputObject;
	public UIInput customGameServerAddress;
	public UIInput customXmppServerAddress;

    void Awake()
    {
        if(Screen.width > Screen.height)
            Screen.SetResolution(1280, 720, true);
        else
            Screen.SetResolution(720, 1280, true);


        if( singleton == null )
            singleton = this;  
        packetQueue = new Queue<Dictionary<byte, object>>();

        Popup_DailyAttendanceCheck.s_IsShow = false;
        Popup_DailyMissionList.s_IsShow = false;
        RuntimeLog.Instance.gameObject.SetActive(true);
        TouchPoint.CreateTouchPoint();
    }

    void Start()
    {
        //StartCoroutine("GetFileVersionList");
        if (LabelBG != null)
        {
            LabelBG.SetActive(false);
        }
        if (WelcomeLabel != null)
        {
            WelcomeLabel.SetActive(false);
        }


        if (FacebookBtn != null)
        {
            FacebookBtn.SetActive(false);
        }


        if (TouchBtn != null)
        {
            TouchBtn.SetActive(false);
        }

        if (TouchCollider != null)
        {
            TouchCollider.SetActive(false);
        }

        //if (progressText != null)
        //{
        //    progressText.gameObject.SetActive(false);
        //}

        if (progressBar != null)
        {
            progressBar.gameObject.SetActive(false);
        }

        if (isForcedReLogin)
        {
            StartCoroutine("SendVersionCheckPacket");
            isForcedReLogin = false;
        }

        Main.mPause = false;

		//
		// Create and initialize Dictionary.
		//
		Dictionary<string, DeckInfo> dictionary = new Dictionary<string, DeckInfo>();
		DeckInfo deckInfo = new DeckInfo();
		deckInfo.deckId = 11111;
		dictionary.Add("cat", deckInfo);
		dictionary.Add("dog", deckInfo);
		dictionary.Add("iguana", deckInfo);
		
		//
		// Copy the Dictionary to a second object.
		//
		Dictionary<string, DeckInfo> copy = new Dictionary<string, DeckInfo>(dictionary);
		copy["cat"] = new DeckInfo(dictionary["cat"]);
		copy["dog"] = new DeckInfo(dictionary["dog"]);
		copy["iguana"] = new DeckInfo(dictionary["iguana"]);
		
		//
		// Change the first Dictionary. It won't change the copy.
		//
//		dictionary.Add("fish", 4);
		dictionary["dog"].deckId = 123446654;
		
		//
		// Display the first Dictionary.
		//
		Debug.LogWarning("--- Dictionary 1 ---");
		foreach (KeyValuePair<string, DeckInfo> pair in dictionary)
		{
			Debug.LogWarning(pair.Value.deckId);
		}
		//
		// Display the second Dictionary.
		//
		Debug.LogWarning("--- Dictionary 2 ---");
		foreach (KeyValuePair<string, DeckInfo> pair in copy)
		{
			Debug.LogWarning(pair.Value.deckId);
		}
    }

    public IEnumerator SendVersionCheckPacket()
    {
		int ReConnectCount = 0;
		singleton.loadingText.text = CStringTableManager.Instance.GetItemById(1612);

        CNetworkManager.Instance.PacketHandler = PacketHandler;

        if (CNetworkManager.Instance.Connected)
            CSceneManager.SendVersionPacket();
        else
        {
            do
            {
                CNetworkManager.Instance.ConnectToServer();
                yield return new WaitForSeconds(1);

                Debug.Log("Reconn --- " + ReConnectCount);

                ReConnectCount++;

                if (ReConnectCount > 10)
                {
                    MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.SERVERERROR, null, null);
                    break;
                }

            } while (!CNetworkManager.Instance.Connected);

            CSceneManager.SendVersionPacket();
        }
    }

    IEnumerator GetFileVersionList()
    {
        Debug.Log("GetFileVersionList - ");
        WWW www = new WWW(CSceneManager.WEB_DOWNLOAD_URL + "/GetDataFileVersion.php");

        yield return www;

        if (www.error == null)
        {
            Debug.Log("www : " + www.text);
        }
        else
        {
            Debug.Log("error : " + www.error);
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (VersionLabel != null)
        {
            UILabel label = VersionLabel.GetComponent<UILabel>();
            if (label != null)
            {
                label.text = CSceneManager.Version;
            }
        }

		if (isFinishedLoadUserData && Tables.isLoadDone)
		{
			GameObject waitSprite = GameObject.Find("Sprite (ui_title_icon_a01)");
			if (waitSprite != null)
			{
				waitSprite.SetActive(false);
			}

			if (LabelBG != null)
			{
				LabelBG.SetActive(true);
			}

			if (WelcomeLabel != null)
			{
				UILabel label = WelcomeLabel.GetComponent<UILabel>();
				if (label != null)
				{
                    label.text = "<" + MyInfo.Instance.NickName + ">님 환영합니다";
					WelcomeLabel.SetActive(true);
				}
			}

//			if (FacebookBtn != null)
//			{
//				FacebookBtn.SetActive(true);
//			}

			if (TouchBtn != null)
			{
				TouchBtn.SetActive(true);
			}

			if (TouchCollider != null)
			{
				TouchCollider.SetActive(true);
			}
		}

        while (packetQueue.Count > 0)
        {
            Dictionary<byte, object> tmpPacket = packetQueue.Dequeue();

            switch ((byte)tmpPacket[0])
            {			
				case (byte)OperationCodes.SC_LOGIN:
				{
                    PC_SC_LOGIN packet = new PC_SC_LOGIN(tmpPacket);
					if (packet.LoginResult == (int)LoginResult.LR_NEW_USER)
					{
						CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
						c.GotoInputNicknameScene();
					}
					else if (packet.LoginResult == (int)LoginResult.LR_LOGIN_OK)
					{
						CSceneManager.LoginSuccess = true;

                        CSceneManager.ServerType = packet.ServerType;
						
				        loadingText.text = CStringTableManager.Instance.GetItemById(1610);
				        RestAPI.singleton.RefreshUserData(ReturnCallback);
                        RestAPI.singleton.GetPVEStageInfo(ReturnCallback);

						//MyInfo.Instance.DBID = packet.DBID; /* DB쪽 ID 저장 */

						//MyInfo.Instance.NickName = packet.NickName;

						//MyInfo.Instance.Diamond = packet.Diamond;
						//MyInfo.Instance.HPPotion = packet.HPPotion;
						//MyInfo.Instance.ResurrectPotion = packet.ResurrectPotion;
						//MyInfo.Instance.Money = packet.Money;
						//MyInfo.Instance.Stamina = packet.Stamina;

						//Debug.LogError(packet.Diamond);
						//Debug.LogError(packet.Money);

						//CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
						////c.StartDownloadResouces();
						//c.RequestDeckInfo();

						CSceneManager.LoadDoneFromWebServer = true;
                        //CNetworkManager.Instance.Disconnect();

                        CSceneManager.NeedToDisconnect = true;   
						if (CSceneManager.NeedToDisconnect)
						{
							CNetworkManager.Instance.Disconnect();
						}
					}
					else
					{
						glog.debug("Login Error!");
					}
				}
				break;
				case (byte)OperationCodes.SC_CHECK_VERSION:
				{
                    PC_SC_CHECK_VERSION packet = new PC_SC_CHECK_VERSION(tmpPacket);
					if (packet.Result == Constants.Instance.RESULT_OK)
					{
						CSceneManager.TimeOffset = packet.TimeStamp - System.DateTime.UtcNow.Ticks;
						CSceneManager.UserInputMode = packet.UserInputMode;
						Debug.Log("Time Offset -- " + CSceneManager.TimeOffset);
					
#if (UNITY_IPHONE || UNITY_ANDROID) && !UNITY_EDITOR
                        if( isCallFacebookInit )
                        {
							loadingText.text = CStringTableManager.Instance.GetItemById(1611);
							CSceneManager.VersionCheckSuccess = true;
							CSceneManager.SendLoginPacket();
                        }
                        else
                        {
                            //Add by HyunSeung(13.09.26)
                            //For Facebook Platform Initializtion.
                            FacebookManager.Init(OnCompleteFacebookInit);
                        }
#else
                        loadingText.text = CStringTableManager.Instance.GetItemById(1611);
						CSceneManager.VersionCheckSuccess = true;
						CSceneManager.SendLoginPacket();
#endif
					  }
					else
					{
						glog.debug("Need reinstall game");
						//CNetworkManager.Instance.Disconnect();
						MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.CLIENTVERSIONMATCH, null, MessagePopupCallback);
					}
				}
				break;
                default:
                    glog.debug("LoadingSceneManager's Packet Handler Unknown Packet Recieved [" + (byte)tmpPacket[0] + "]");
                    break;
            }
        }
    }

	public void OnTouch()
	{
		TouchCollider.collider.enabled = false;
		TouchCollider.SetActive(false);
		CSceneManager c = GameObject.FindObjectOfType(typeof(CSceneManager)) as CSceneManager;
		c.GoToWaitroomScene();
	}

    public static bool PacketHandler(Dictionary<byte, object> _packet)
    {
        if (packetQueue != null)
        {
            packetQueue.Enqueue(_packet);
            return true;
        }

        return false;
    }
	
	bool isCallFacebookInit = true;
	void OnCompleteFacebookInit(bool isSuccess)
	{
		Debug.LogError(FB.IsLoggedIn);
		//Add By HyunSeung(13.09.26)
//        if (!FB.IsLoggedIn)
//            FacebookBtn.SetActive(true);
//        else
//        {
//            if (facebookUserImageObject == null)
//                Debug.LogError("null");
//            if(facebookUserNameText == null)
//                Debug.LogError("null");
                    
#if !UNITY_EDITOR
//            FacebookManager.GetMyProfile();
//            FacebookManager.GetMyThumnail(facebookUserImageObject.renderer.material.mainTexture);
#endif
//		}
		
		loadingText.text = CStringTableManager.Instance.GetItemById(1611);
		CSceneManager.VersionCheckSuccess = true;
		CSceneManager.SendLoginPacket();
		
		isCallFacebookInit = true;
	}

    public void SetFacebookUserName(string name)
    {
        facebookUserNameText.text = name;
    }

    void ReturnCallback(Hashtable returnData)
    {
        switch ((RestAPIProtocol)returnData["protocol"])
        {
            case RestAPIProtocol.REFRESHUSERINFO:
                RestAPI.singleton.GetCurrentStaminaInfo(ReturnCallback);
                break;
            case RestAPIProtocol.GETCURRENTSTAMINAINFO:
                loadingText.text = CStringTableManager.Instance.GetItemById(1609);
                RestAPI.singleton.GetMyUnitList(ReturnCallback);
                break;
            case RestAPIProtocol.GETMYUNITLIST:
                loadingText.text = CStringTableManager.Instance.GetItemById(1608);
                RestAPI.singleton.RefreshMyDeckInfo(ReturnCallback);
                break;
            case RestAPIProtocol.REFRESHMYDECKINFO:
				if(loadingText!=null && loadingText.gameObject!=null)
                	loadingText.gameObject.SetActive(false);
				else
					Debug.LogError("loadingText null");
                RestAPI.singleton.GetMyFriendList(ReturnCallback);
                isFinishedLoadUserData = true;
                break;
            case RestAPIProtocol.PUTUSERDATA:
                break;
            case RestAPIProtocol.GETPVESTAGEINFO:
                break;
                
        }
    }
	
	void MessagePopupCallback(MESSAGEPOPUPTYPE type, bool isYes)
	{
		if( type == MESSAGEPOPUPTYPE.CLIENTVERSIONMATCH )
		{
			if( isYes )
			{
				Application.OpenURL("http://211.189.163.178:8080/deploy/");
			}
		}
		else if( type == MESSAGEPOPUPTYPE.SERVERERROR )
		{
			CSceneManager.LoginSuccess = false;
			CSceneManager.VersionCheckSuccess = false;
			CSceneManager.manager.GoToLoadingScene();
		}
	}

	int inputCount = 0;
	public void CheckInputForCustomServerAddress()
	{
		if( inputCount++ < 4 )
			return;
		else
		{
			TouchCollider.collider.enabled = false;
			titleImage.SetActive(false);
			customServerAddressInputObject.SetActive(true);
		}
	}

	public void ChangeToCustomServerAddress()
	{
		if( string.IsNullOrEmpty(customGameServerAddress.value) || string.IsNullOrEmpty(customXmppServerAddress.value) ) return;

		CSceneManager.BuildType = 2;
		PlayerPrefs.SetString("CustomGameServerAddress", customGameServerAddress.value);
		PlayerPrefs.SetString("CustomXmppServerAddress", customXmppServerAddress.value);
        CNetworkManager.Instance.SetServerAddress();
		CSceneManager.manager.GoToLoadingScene();
	}

	public void ChangeToDevServerAddress()
	{
		CSceneManager.BuildType = 0;
		PlayerPrefs.DeleteKey("CustomGameServerAddress");
		PlayerPrefs.DeleteKey("CustomXmppServerAddress");
        CNetworkManager.Instance.SetServerAddress();
		CSceneManager.manager.GoToLoadingScene();
	}

	public void ChangeToQAServerAddress()
	{
		CSceneManager.BuildType = 1;
		PlayerPrefs.DeleteKey("CustomGameServerAddress");
		PlayerPrefs.DeleteKey("CustomXmppServerAddress");
        CNetworkManager.Instance.SetServerAddress();
		CSceneManager.manager.GoToLoadingScene();
	}

//	void OnGUI()
//	{
//		System.TimeSpan span = System.TimeSpan.FromSeconds(Time.time);
//		GUILayout.Label(span.Seconds.ToString());
//		if( span.Seconds == 10 )
//			Debug.LogError("Time Over!");
//	}
}
